var http = require('http');  
var push = require('./pushApp');
var url = require('url');
var util = require('util');
var qiniu = require('./qiniu')
var upTime;
var oneSecond = 30 * 1000; // one second = 1000 x 1 ms
var isok = true;
var isLongTime = true;
setInterval(function()  {
	testServer();

}, oneSecond);

http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/plain'});
	var path = url.parse(req.url).pathname;
	if (path == '/version'){
		var data = '1'  // data == 2停止.
		var resdata = {oldPay: data};
		res.end(JSON.stringify(resdata));
	}else{
		var data = '';	
    	if (isok) {
    		data ='1';
    		var currTime = new Date().getTime();
    		if (currTime - upTime > 31000) {
    			data ='2';
    		}
    	}else{
    		data = '3';
   		}
		var resdata = {severState: data};
    	res.end(JSON.stringify(resdata));
		}
}).listen(6789);



function  testServer(){

	var req = http.request("http://www.yukicomic.com/v4/data/findmiaoshalist.action", function (res) {  
    	var date = new Date(); 

    	clearInterval(date);
    	if (res.statusCode == '200') {
    		upTime = new Date().getTime();

		if(!isok || isLongTime){
			push.pushCress('服务器好了\n王缙最帅');
		}
        if (!isok) {
          isok = true;
        }
		if (isLongTime){
			isLongTime = false;
		}
		
    	}
	});  

	req.on('error', function (e) {  
   		 if (isok) {
          isok = false;
		  gotoZGRSMS();
          push.pushCress('服务器挂了\n王缙最帅');
        }
	});  
	req.end();  

	var currTime = new Date().getTime();
	if ((currTime - upTime > 31000) && !isLongTime) {
		isLongTime = true;
    	push.pushCress('服务器超时了,马上就要挂了\n王缙最帅');
    }

}

//发送短信给润润..
function gotoZGRSMS() {
	var UrlString = 'http://utf8.sms.webchinese.cn/?Uid=yukicomic&Key=9f0f8253b11433418140&smsMob=13685133170&smsText=%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%8C%82%E4%BA%86,%E5%BF%AB%E7%9C%8B%E7%9C%8B%%3E_%3C%';
	var req1 = http.request(UrlString, function (res1){
				console.log('SMSZGR: ' + res1.statusCode);  
    	 });
     req1.end();
}
